package org.john.jackson;

import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import java.io.IOException;
import java.util.HashMap;

/**
 * Created by adsame on 17-3-21.
 */
public class JsonTestJackson {

    public static class QuantoneToutiaoElement {

        private static final String KEY_TAG = "key";
        private static final String VALUE_TAG = "value";

        private final String key;
        private final String value;

        public QuantoneToutiaoElement(
                @JsonProperty(KEY_TAG) String key,
                @JsonProperty(VALUE_TAG) String value) {
            this.key = key;
            this.value = value;
        }

        @JsonProperty(KEY_TAG)
        public String getKey() {
            return key;
        }

        @JsonProperty(VALUE_TAG)
        public String getValue() {
            return value;
        }
    }

    public static void main(String args[]) {
        testBasic();
        QuantoneToutiaoElement tt[] = {
                new QuantoneToutiaoElement("title", "test title"),
                new QuantoneToutiaoElement("source", "source content"),
                new QuantoneToutiaoElement("desc", "description"),
                new QuantoneToutiaoElement(null, null)
        };
        try {
//            System.out.println(tt.getKey() + "," + tt.getValue());
//            String s = objectToJson((QuantoneToutiaoElement)tt);
            System.out.println(objectToJson(tt));
            testBasic();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void testBasic() {
        HashMap<String, String> map = new HashMap();
        map.put("idfa", "difoew");
        map.put("imei", "32794729");
        map.put("androidId", "fjeiowi");
        map.put("mac", "ba:ei:ei:sd");
        map.put("macMd5", "");
        ObjectMapper obj = new ObjectMapper();
        try {
            String str = obj.writeValueAsString(map);
            System.out.println(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String s = "{\"key\":\"title\",\"tmax\":100,\"value\":\"test title\"}";
        try {
            QuantoneToutiaoElement el = obj.readValue(s, QuantoneToutiaoElement.class);
            System.out.println(el.getKey() + "," + el.getValue());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static <T> String objectToJson(T object) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
        return mapper.writeValueAsString(object);
    }
}
